package cn.edu.fzu.homemaking.controller;

import cn.edu.fzu.homemaking.api.OrderApi;
import cn.edu.fzu.homemaking.api.WalletApi;
import cn.edu.fzu.homemaking.common.SessionConstant;
import cn.edu.fzu.homemaking.domain.entity.User;
import cn.edu.fzu.homemaking.domain.entity.UserDemand;
import cn.edu.fzu.homemaking.domain.entity.UserWallet;
import cn.edu.fzu.homemaking.domain.enums.CommentStatusEnum;
import cn.edu.fzu.homemaking.domain.enums.DemandStatusEnum;
import cn.edu.fzu.homemaking.domain.enums.OrderStatusEnum;
import cn.edu.fzu.homemaking.domain.vo.UserDemandVo;
import cn.edu.fzu.homemaking.exception.ServiceException;
import cn.edu.fzu.homemaking.service.DemandService;
import cn.edu.fzu.homemaking.util.ResultUtil;
import cn.edu.fzu.homemaking.web.Result;
import cn.edu.fzu.homemaking.web.RetCode;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Author jiebin
 * @Date 2023/4/12
 */
@RestController
@RequestMapping("/api/user/auth/order")
@Api(tags = "订单管理")
public class OrderController {
    @Resource
    private OrderApi orderApi;
    @Resource
    private WalletApi walletApi;
    @Resource
    private DemandService demandService;

    @PostMapping("/insert")
    @ApiOperation(value = "用户主动下订单", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true),
            @ApiImplicitParam(name = "serverId", value = "服务标签id", required = true),
            @ApiImplicitParam(name = "description", value = "服务标签名称",required = true),
            @ApiImplicitParam(name = "customerName", value = "顾客名",required = true),
            @ApiImplicitParam(name = "address", value = "服务地址", required = true),
            @ApiImplicitParam(name = "phone", value = "联系电话", required = true),
            @ApiImplicitParam(name = "email", value = "邮箱地址", required = true),
            @ApiImplicitParam(name = "startTime", value = "约定服务时间",required = true),
            @ApiImplicitParam(name = "price", value = "服务价格", required = true),
            @ApiImplicitParam(name = "qty", value = "数量", required = true)
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result insert(Long companyId, Long serverId, String description, String customerName,
                         String address, String phone, String email, String startTime, BigDecimal price, Integer qty, HttpServletRequest request){
        User user = (User)request.getSession().getAttribute(SessionConstant.ACCOUNT);
        List<UserDemandVo> list = demandService.list(user.getId(),null,null,
                null,null, DemandStatusEnum.WAIT);
        BigDecimal total = price.multiply(new BigDecimal(qty));
        for (UserDemand userDemand: list) {
            total = total.add(userDemand.getPrice());
        }
        total = total.add(new BigDecimal(orderApi.getUnPayMoney().getValue().toString()));
        UserWallet userWallet = ResultUtil.parseValue(walletApi.getWallet(), UserWallet.class);
        if (total.compareTo(userWallet.getSurplus())==1){
            throw new ServiceException("用户钱包余额不支持发布新的需求，请及时充值！");
        }
        orderApi.insert(companyId, user.getId(), null, serverId, description, customerName, address,
                phone, email, startTime, price, qty);
        return new Result(RetCode.SUCCESS,"生成订单成功");
    }

    @GetMapping("list")
    @ApiOperation(value = "获取订单列表",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "demandId", value = "需求id"),
            @ApiImplicitParam(name = "serverId", value = "服务id"),
            @ApiImplicitParam(name = "startTime", value = "开始时间（服务约定时间）"),
            @ApiImplicitParam(name = "endTime", value = "结束时间（服务约定时间）"),
            @ApiImplicitParam(name = "status", value = "订单状态"),
            @ApiImplicitParam(name = "commentStatus", value = "订单评价状态"),
            @ApiImplicitParam(name = "pageNum", required = true),
            @ApiImplicitParam(name = "pageSize", required = true)
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result list(Long demandId, Long serverId, String startTime, String endTime,
                       OrderStatusEnum status, CommentStatusEnum commentStatus, Integer pageNum, Integer pageSize){
        return orderApi.list(null,demandId, serverId, startTime, endTime, status, commentStatus, pageNum, pageSize);
    }

    @GetMapping("selectByOrderId")
    @ApiOperation(value = "根据订单id获取订单",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", required = true)
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result selectByOrderId(String orderId){
        return orderApi.selectByOrderId(orderId);
    }

    @GetMapping("cancel")
    @ApiOperation(value = "取消订单", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", required = true)
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result cancel(String orderId){
        orderApi.updateStatus(orderId, OrderStatusEnum.CANCEL);
        return new Result(RetCode.SUCCESS,"取消订单成功");
    }
}
